package com.woniu.uums.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.woniu.common.dto.ZyManageDto;
import com.woniu.common.utils.ResponseData;
import com.woniu.uums.pojo.FaceDto;
import com.woniu.uums.pojo.ZyManage;
import com.woniu.uums.service.FaceSearch;
import com.woniu.uums.service.ZyManageService;
import com.woniu.uums.utils.FaceAdd;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.woniu.common.constant.FinanceConstant.JWT.TOKEN_HEADER;

@RestController
public class FaceController {
    @Autowired
    private ZyManageService zyManageService;
    /**
     * 注册
     * @return json
     */
    @PostMapping("/faceReg")
    public String FaceRegister(@RequestBody FaceDto params){
        System.out.println("---------faceregister-------");
        System.out.println(params.getBase());
        String result = FaceAdd.add(params);
        System.out.println("-----人脸注册成功");
        return result;
    }

    /**
     * 登录
     * @return json
     */
    @RequestMapping("/faceLog")
    public ResponseData<?> FaceLogin(@RequestBody FaceDto base){
        String msg = FaceSearch.faceSearch(base.getBase());
        JSONObject json = JSONObject.parseObject(msg);
        if(ObjectUtil.isEmpty(json.getJSONObject("result"))){
            return new ResponseData<>().fail();
        }
        JSONArray userList = null;
            userList = json.getJSONObject("result").getJSONArray("user_list");
        String token=null;
        if (userList != null && !userList.isEmpty()) {
            JSONObject userData = userList.getJSONObject(0);
             String id = (String) userData.get("user_id");
            String manageNickName = (String) userData.get("user_info");
            ZyManageDto zyManageDto = new ZyManageDto();
            zyManageDto.setId(id);
            zyManageDto.setManageNickName(manageNickName);
            Map<String,Object> map = new HashMap<>(1);
            map.put("zyManage",zyManageDto);
            token = JWTUtil.createToken(map, TOKEN_HEADER.getBytes());
            float score = userData.getFloatValue("score");
            if (score < 80){
                System.out.println("人脸匹配失败，请重新刷脸登录");
                return new ResponseData<>().fail();
            }
            System.out.println("相似度："+score);
        } else {
            System.out.println("未找到用户score数据");
        }
        return new ResponseData<>().success(token);
    }
}
